<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>受控组件</title>
    </head>
    <body>
        <div id="root"></div>

        <script src="../js/react.development.js"></script>
        <script src="../js/react-dom.development.js"></script>
        <script src="../js/babel.min.js"></script>

        <script type="text/babel">
            class App extends React.Component {
                //1. 声明state
                state = {
                    username: 'abc',
                    password: 'xxx'
                }

                render() {
                    return (
                        <div>
                            <h2>登录</h2>
                            <form action="" onSubmit={this.submit}>
                                {/** 2. 将 input 的 value 设置为 state 中的属性值*/}
                                {/** 3. 为 input 元素添加 onChange 事件*/}   {/** onChange 当表单元素值, 发生改变时, 触发的事件, 是 React 封装的, 原生不存在这个事件 **/}
                                用户名: <input type="text"  value={this.state.username}  onChange={this.saveUserName} />
                                <br />
                                密码: <input type="text" value={this.state.password} onChange={this.savePassword}/>
                                <br />
                                <button onClick={this.login}>登录</button>
                            </form>
                        </div>
                    );
                }

                login = () => {
                    console.log('用户名: '+this.state.username);    
                    console.log('密码:'+this.state.password);    
                }

                savePassword = (e) => {
                    this.setState({
                        password: e.target.value
                    })
                }

                //4. 添加事件回调
                saveUserName = (e) => {
                    //事件触发后, 获取 input 的值
                    // console.log(e.target.value);
                    //5. 修改 state 中的状态
                    this.setState({
                        username: e.target.value
                    })
                }

                submit = (e) => {
                    e.preventDefault();
                }
            }

            ReactDOM.render(<App />, document.querySelector("#root"));
        </script>
    </body>
</html>
